package com.example.qimo.controller;
import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.qimo.commom.Result;

import com.example.qimo.dao.*;
import com.example.qimo.dao.Menu;
import com.example.qimo.entsty.*;

import com.example.qimo.mapper.AuthMapper;
import com.example.qimo.mapper.RoleMapper;
import com.example.qimo.service.*;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class Api {
    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;
    @Resource
    private StudentService studentService;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private AuthMapper authMapper;
    @Resource
    private PermissionService permissionService;
    @GetMapping("/index")
    public String index() {
        return "hello";
    }

    @PostMapping("/dologin")
    public Result dologin(String username, String password, boolean rememberMe) {
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        System.out.println(rememberMe);//rememberMe为true则shiro会帮我们记住用户的登录状态
        try {
            subject.login(token);
            User user = (User) subject.getPrincipal();
            subject.getSession().setAttribute("user", user);
            return Result.success("登录成功");
        } catch (UnknownAccountException e) {
            return Result.error("不存在的账号");
        } catch (LockedAccountException e) {
            return Result.error("账号被锁定");
        } catch (DisabledAccountException e) {
            return Result.error("账号被禁用");
        }

    }

    @GetMapping("/unauth")
    public Result unauth() {
        return Result.error("未授权，无法访问！");
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success("ok");
    }

    @GetMapping("/menu")
    public List<Menu> menu() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        return menuService.getMenu(user.getRole());
    }

    @PostMapping("/reg")
    public Result reg(@RequestBody UserDto u) {
        try {
            Validator.validateNotEmpty(u.getUname(), "用户名不能为空");
            Validator.validateNotEmpty(u.getPwd(), "密码不能为空");
            Validator.validateNotEmpty(u.getMobile(), "手机号不能为空");
            Validator.validateNotEmpty(u.getMobile(), "手机号格式错误");
            User huser = userService.getByName(u.getUname());
            if (huser != null) {
                throw new Exception("用户已存在");
            }
            User user = new User();
            user.setUsername(u.getUname());
            user.setPassword(DigestUtil.md5Hex(u.getPwd()));
            user.setPhone(u.getMobile());
            userService.save(user);
            return Result.success("ok");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/student_add")
    public Result addStudent(@RequestBody StudentDto t) {
        Student student = new Student();
        student.setName(t.getName());
        student.setAddr(t.getAddr());
        student.setSno(t.getXuehao());
        student.setSex(t.getSex());
        student.setPhone(t.getMobile());
        studentService.save(student);
        return Result.success(student);
    }

    @PostMapping("/student_list")
    public Result studentList() {
        List<Student> list = studentService.list();
        List<StudentDto> list2 = new ArrayList<>();
        for (Student s : list) {
            StudentDto studentDto = new StudentDto();
            studentDto.setName(s.getName());
            studentDto.setAddr(s.getAddr());
            studentDto.setSex(s.getSex());
            studentDto.setXuehao(s.getSno());
            studentDto.setMobile(s.getPhone());
            studentDto.setId(s.getId());
            list2.add(studentDto);
        }
        return Result.success(list2);
    }

    @DeleteMapping("/student_delete/{id}")
    public Result studentDelete(@PathVariable Integer id) {
        boolean res = studentService.removeById(id);
        if (res) {
            return Result.success("ok");
        } else {
            return Result.success("err");
        }
    }
//    @PostMapping("/menu_list")
//    public Result menuList(){
//        List<Menu> list = menuService.list();
//        List<MenuDto> list2 = new ArrayList<>();
//        for (Menu m : list) {
//            MenuDto menuDto = new MenuDto();
//            menuDto.setTitle(m.getTitle());
//            menuDto.setIcon(m.getIcon());
//            menuDto.setPid(m.getPid());/[
//            menuDto.setRole(m.getRole());
//            list2.add(menuDto);
//        }
//        return Result.success(list2);
//    }
//
    @PutMapping("/student_update")
    public Result updateStudent(@RequestBody StudentDto t) {
        try {
//           Validator.validateNotEmpty(u.getUname(),"用户名不能为空");
//           Validator.validateNotEmpty(u.getPwd(),"密码不能为空");
//           Validator.validateNotEmpty(u.getMobile(),"手机号不能为空");
//           Validator.validateNotEmpty(u.getMobile(),"手机号格式错误");
            Student student = new Student();
            student.setName(t.getName());
            student.setAddr(t.getAddr());
            student.setSex(t.getSex());
            student.setPhone(t.getMobile());
            student.setSno(t.getXuehao());
            student.setId(t.getId());
            studentService.updateById(student);
            return Result.success("ok");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
//
    @GetMapping("/menu_list")
    public Result menu_list() {
        List<Menu> list = menuService.list();
        List<MenuDto> list2 = new ArrayList<>();
        for (Menu s : list) {
            MenuDto mdto = new MenuDto();
            mdto.setTitle(s.getTitle());
            mdto.setAuth(s.getAuth());
            mdto.setIcon(s.getIcon());
            mdto.setPid(s.getPid());
            mdto.setPath(s.getPath());
            mdto.setId(s.getId());
            list2.add(mdto);
        }
        return Result.success(list2);
    }

    @PostMapping("/add_menu")
    public Result addMenu(@RequestBody MenuDto t) {
        Menu menu = new Menu();
        menu.setId(t.getId());
        menu.setTitle(t.getTitle());
        menu.setIcon(t.getIcon());
        menu.setAuth(t.getAuth());
        menu.setPath(t.getPath());
        System.out.println(t);
        menuService.save(menu);
        return Result.success(menu);
    }

    @DeleteMapping("/menu_delete/{id}")
    public Result menuDelete(@PathVariable Integer id) {
        boolean res = menuService.removeById(id);
        if (res) {
            return Result.success("ok");
        } else {
            return Result.error("err");
        }

    }

    @PutMapping("/menu_update")
    public Result menuUpdate(@RequestBody MenuDto t) {
        try {
//            Validator.validateNotEmpty(t.getName(), "用户名不能为空");
//            Validator.validateNotEmpty(t.getSex(), "密码不能为空");
//            Validator.validateNotEmpty(t.getMobile(), "手机号不能为空");
//            Validator.validateMobile(u.getMobile(), "手机号格式错误");
            Menu menu = new Menu();
            menu.setTitle(t.getTitle());
            menu.setIcon(t.getIcon());
            menu.setAuth(t.getAuth());
            menu.setPath(t.getPath());
            menu.setId(t.getId());
            menuService.updateById(menu);
            return Result.success("ok");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

    }
    @GetMapping("/permission_list/{page}")
    public Result permission_list(@PathVariable Integer page) {
        if (page == 0) {
            page = 1;
        }
        IPage<Permission> pobj = permissionService.getStudentList(page);
        List<Permission> list = pobj.getRecords();
        long pn = pobj.getPages();
        return Result.success(Map.of("list", list, "page", pn));
    }
    @GetMapping("/permission_list")
    public Result permissionList() {
        List<Permission> list = permissionService.list();
        List<PermissionDto> list2 = new ArrayList<>();
        for (Permission s : list) {
            PermissionDto dto = new PermissionDto();
            dto.setId(s.getId());
            dto.setPermitName(s.getPermitName());
            dto.setType(s.getType());
            dto.setRemark(s.getRemark());
            dto.setDengji(s.getDengji());
            list2.add(dto);
        }
        return Result.success(list2);
    }

    @PostMapping("/add_permission")
    public Result addPermission(@RequestBody PermissionDto t) {
        Permission permission = new Permission();
        permission.setId(t.getId());
        permission.setPermitName(t.getPermitName());
        permission.setType(t.getType());
        permission.setRemark(t.getRemark());
        permission.setDengji(t.getDengji());
        permissionService.save(permission);
        return Result.success(permission);
    }

    @DeleteMapping("/permission_delete/{id}")
    public Result permissionDelete(@PathVariable Integer id) {
        boolean res = permissionService.removeById(id);
        if (res) {
            return Result.success("ok");
        } else {
            return Result.error("err");
        }
    }

    @PutMapping("/permission_update")
    public Result permissionUpdate(@RequestBody PermissionDto t) {
        try {
            Permission permission = new Permission();
            permission.setId(t.getId());
            permission.setPermitName(t.getPermitName());
            permission.setType(t.getType());
            permission.setRemark(t.getRemark());
            permission.setDengji(t.getDengji());
            permissionService.updateById(permission);
            return Result.success("ok");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    @GetMapping("/role_list")
    public Result roleList() {
        List<RoleView> list =roleMapper.getRoleAuthList();

        return Result.success(list);
    }

    @PostMapping("/add_role")
    @Transactional
    public Result addRole(@RequestBody RoleDto a) {
        System.out.println(a);
        try{
            LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Role::getRoleName, a.getRoleName());
            Role r = roleMapper.selectOne(queryWrapper);
            if(r == null){
                Role role = new Role();
                role.setRoleName(a.getRoleName());
                role.setRemark(a.getRoleRemark());
                role.setCreateTime(new Date());
                roleService.save(role);
                System.out.println(role);
                String pi =a.getPermitId();
                String[] arr = pi.split(",");
                List<Auth> list = new ArrayList<>();
                for(String i: arr){
                    if(i.isEmpty()){
                        continue;
                    }
                    System.out.printf(i+"----");
                    Auth auth = new Auth();
                    auth.setRoleId(role.getId());
                    auth.setPermitId(Integer.parseInt(i));

                    auth.setCreateTime(new Date());
                    auth.setUpdateTime(new Date());
                    list.add(auth);
                }
                authMapper.insert(list);
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }

        return Result.success(null);
    }
    @DeleteMapping("/role_delete/{id}")
    public Result role_delete(@PathVariable Integer id) {
        boolean res= roleService.removeById(id);
        if(res){
            LambdaQueryWrapper<Auth> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Auth::getRoleId, id);
            return Result.success("ok");
        }else {
            return Result.error("err");
        }
    }
    @PutMapping("/role_update")
    public Result role_update(@RequestBody RoleDto t) {
        try {
            if(roleService.removeById(t.getId())){
                LambdaQueryWrapper<Auth> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Auth::getRoleId, t.getId());
                authMapper.delete(queryWrapper);
            }
            Role role = new Role();
            role.setRoleName(t.getRoleName());
            role.setRemark(t.getRoleRemark());
            role.setCreateTime(new Date());
            roleService.save(role);
            String pi =t.getPermitId();
            String[] arr = pi.split(",");
            List<Auth> list = new ArrayList<>();
            for(String i: arr) {
                if (i.isEmpty()) {
                    continue;
                }
                Auth auth = new Auth();
                auth.setRoleId(role.getId());
                auth.setPermitId(Integer.parseInt(i));
                auth.setCreateTime(new Date());
                auth.setUpdateTime(new Date());
                list.add(auth);
            }
            authMapper.insert(list);
            return Result.success("ok");
        }catch (Exception e){

            return Result.error(e.getMessage());
        }
    }
//    @GetMapping("/user_list")
//    public Result user_list() {
//        List<User> list = userService.list();
//        List<UserDto> list2 = new ArrayList<>();
//        for (User s : list) {
//            UserDto u = new UserDto();
//            u.setUname(s.getUsername());
//            u.setPhone(s.getPhone());
//            u.setStatus(s.getStatus());
//            u.setRole(s.getRole());
//            u.setUpdateTime(s.getUpdateTime());
//            list2.add(u);
//        }
//        return Result.success(list2);
//    }
//    @GetMapping("/user_list/{page}")
//    public Result user_list(@PathVariable Integer page) {
//        if (page == 0) {
//            page = 1;
//        }
//        IPage<User> pobj = userService.getStudentList(page);
//        List<User> list = pobj.getRecords();
//        long pn = pobj.getPages();
//        List<UserDto> list2 = new ArrayList<>();
//        for (User s : list) {
//            UserDto dto = new UserDto();
//            dto.setId(s.getId());
//            dto.setUname(s.getUsername());
//            dto.setMobile(s.getPhone());
//            dto.setRole(s.getRole());
//            dto.setStatus(s.getStatus());
//            dto.setCreateTime(s.getCreateTime());
//            list2.add(dto);
//        }
//        return Result.success(Map.of("list", list2, "page", pn));
//    }
//    @PutMapping("/user_update")
//    public Result user_update(@RequestBody UserDto t) {
//        try {
//            User user = new User();
//            user.setRole(t.getRole());
//            user.setStatus(t.getStatus());
//            user.setId(t.getId());
//            userService.updateById(user);
//            return Result.success("ok");
//        }catch (Exception e){
//            return Result.error(e.getMessage());
//        }
//    }
//    @GetMapping("/getCx/{name}")
//    public Result getCx(@PathVariable String name) {
//        System.out.println(111);
//        List<User> list = userService.saveUserCx(name);
//        List<UserDto> list2 = new ArrayList<>();
//        for (User s : list) {
//            UserDto dto = new UserDto();
//            dto.setId(s.getId());
//            dto.setUname(s.getUsername());
//            dto.setMobile(s.getPhone());
//            dto.setRole(s.getRole());
//            dto.setStatus(s.getStatus());
//            dto.setCreateTime(s.getCreateTime());
//            list2.add(dto);
//        }
//        return Result.success(list2);
//    }
}

